package com.doctor.ui.homedoctor;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import com.doctor.adapter.ShowImageAdapter;
import com.doctor.comm.ConstConfig;
import com.doctor.comm.DialogHelper;
import com.doctor.comm.FileHelper;
import com.doctor.comm.ImageHelper;
import com.doctor.comm.LoadingTip;
import com.doctor.comm.DialogHelper.NoticeDialogCallback;
import com.doctor.comm.ImageHelper.TakePictureCallback;
import com.doctor.database.DbOperator;
import com.doctor.ui.BaseFragment;
import com.doctor.ui.DragImageActivity;
import com.doctor.ui.R;
import com.doctor.view.NoScrollGridView;

public class AddDiseaseRecordFrag extends BaseFragment{

	/**
	 * 新增病历
	 */
	
	private Context context;
	private Calendar calendar;
	private TextView tvTime,uploadBtn,takePhotoBtn;
	private EditText tvComplain,tvPresent,tvPrescription,tvPhysicalCheck,tvAuxiliaryCheck,tvInitialDiagnosis,etDoctorAdvice;
	private LinearLayout saveBtn,cancelBtn;
	private int patientId;
	private Click click;
	private SimpleDateFormat dateFormat;
	
	private Uri imageUri;
	//显示图片之用
	private NoScrollGridView gridView;
	private ShowImageAdapter adapter;
	private List<String> beanList;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		context=getActivity();
		calendar=Calendar.getInstance();
		patientId=getArguments().getInt(ConstConfig.ID);
		click=new Click();
		dateFormat=new SimpleDateFormat("yyyy-MM-dd");
		
		View view=inflater.inflate(R.layout.add_disease_record, container, false);
		initiaView(view);
		
		return view;
	}
	
	
	@Override
	protected void initiaView(View view) {
		// TODO Auto-generated method stub
		tvTime=(TextView) view.findViewById(R.id.tv_time);
		tvTime.setOnClickListener(click);
		
		uploadBtn=(TextView) view.findViewById(R.id.uploadBtn);
		uploadBtn.setOnClickListener(click);
		
		takePhotoBtn=(TextView) view.findViewById(R.id.takePhotoBtn);
		takePhotoBtn.setOnClickListener(click);
		
		tvComplain=(EditText) view.findViewById(R.id.tv_complain);
		tvPresent=(EditText) view.findViewById(R.id.tv_present);
		tvPhysicalCheck=(EditText) view.findViewById(R.id.tv_physical_check);
		tvAuxiliaryCheck=(EditText) view.findViewById(R.id.tv_auxiliary_check);
		tvInitialDiagnosis=(EditText) view.findViewById(R.id.tv_initial_diagnosis);
		tvPrescription=(EditText) view.findViewById(R.id.tv_prescription);
		etDoctorAdvice = (EditText) view.findViewById(R.id.et_doctor_advice);
		saveBtn=(LinearLayout) view.findViewById(R.id.saveBtn);
		saveBtn.setOnClickListener(click);
		
		cancelBtn=(LinearLayout) view.findViewById(R.id.cancelBtn);
		cancelBtn.setOnClickListener(click);
		
		gridView=(NoScrollGridView) view.findViewById(R.id.gridView);
		beanList=new ArrayList<String>();
		adapter=new ShowImageAdapter(context, beanList);
		gridView.setAdapter(adapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				String picPath=(String) arg1.getTag(R.id.bean_tag);
				Intent intent=new Intent(getActivity(),DragImageActivity.class);
				intent.putExtra(getString(R.string.uri), picPath);
				startActivity(intent);
			}
		});
		gridView.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, final View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				
				DialogHelper.noticeDialog(context, null, new NoticeDialogCallback() {	
					@Override
					public void onClicked(int position) {
						// TODO Auto-generated method stub
						if (position==1) {
							String pic=(String) arg1.getTag(R.id.bean_tag);
							adapter.removeBean(pic);
						}
					}
				});
				return true;
			}
		});
	}
	
	private class Click implements OnClickListener{
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (v==tvTime) {
				DialogHelper.showDatePickerDialog(context, tvTime, calendar, false);
			} else if (v == uploadBtn) {
				if (adapter.getCount() >= 10)
					LoadingTip.showToast(context, "最多保存10张图片！");
				else
					ImageHelper.selectPicture(AddDiseaseRecordFrag.this, ConstConfig.CHOOSE_PICTURE,null);
			} else if (v == takePhotoBtn) {
				if (adapter.getCount() >= 10) {
					LoadingTip.showToast(context, "最多保存10张图片！");
				} else {
					ImageHelper.selectPicture(AddDiseaseRecordFrag.this, ConstConfig.TAKE_PICTURE,new TakePictureCallback() {					
						@Override
						public void onGetImageName(Uri imageUri) {
							// TODO Auto-generated method stub
							AddDiseaseRecordFrag.this.imageUri=imageUri;
						}
					});
				}
				
			} else if (v==cancelBtn) {
				getActivity().getSupportFragmentManager().popBackStack();
			} else if (v==saveBtn) {
				String complain = tvComplain.getText().toString().trim();
				if (complain == null || "".equals(complain)) {
					Toast.makeText(context, "请填写主诉！", Toast.LENGTH_SHORT).show();
					return;
				}
				
				if (patientId<1001) {
					Toast.makeText(context, "添加失败！", Toast.LENGTH_SHORT).show();
					return;
				}
				
				
				String time = tvTime.getText().toString();
				if (time == null || time.length() <= 0) {
					Toast.makeText(context, "请选择时间！", Toast.LENGTH_SHORT).show();
					return;
				}
				ContentValues values=new ContentValues();
				values.put("_complain", complain);
				values.put("_patient_id", patientId);
				values.put("_time", time);
				
				String present=tvPresent.getText().toString().trim();
				if (present!=null && !"".equals(present)) {
					values.put("_present", present);
				}
				
				String physicalCheck=tvPhysicalCheck.getText().toString().trim();
				if (physicalCheck!=null && !"".equals(physicalCheck)) {
					values.put("_physical_check", physicalCheck);
				}
				
				String auxiliaryCheck=tvAuxiliaryCheck.getText().toString().trim();
				if (auxiliaryCheck!=null && !"".equals(auxiliaryCheck)) {
					values.put("_auxiliary_check", auxiliaryCheck);
				}
				
				String initialDiagnosis=tvInitialDiagnosis.getText().toString().trim();
				if (initialDiagnosis!=null && !"".equals(initialDiagnosis)) {
					values.put("_initial_diagnosis", initialDiagnosis);
				}
				
				String prescription=tvPrescription.getText().toString().trim();
				if (prescription!=null && !"".equals(prescription)) {
					values.put("_prescription", prescription);
				}
				
				String doctorAdvice = etDoctorAdvice.getText().toString().trim();
				if (doctorAdvice != null && !"".equals(doctorAdvice)) {
					values.put("_doctor_advice", doctorAdvice);
				}
				
				if (adapter.getAll()!=null && !"".equals(adapter.getAll())) {
					values.put("_image", adapter.getAll());
				}
				
				values.put("_operation", ConstConfig.OPERATION_ADD);
				
				long row=DbOperator.getInstance(context).insertData(ConstConfig.DISEASE_RECORD_TABLE, values);
				if (row>0) {
					Toast.makeText(context, "添加成功！", Toast.LENGTH_SHORT).show();
					getActivity().getSupportFragmentManager().popBackStack();
				} else {
					Toast.makeText(context, "添加失败！", Toast.LENGTH_SHORT).show();
				}
			}	
		}		
	}
	
	
	//选择图片或拍照完成后返回图片路径
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		//-1=RESULT_OK
		if (resultCode==-1) {
			Uri imageUri = null;	
			switch (requestCode) {
			case ConstConfig.CHOOSE_PICTURE:
				if (data!=null) {
					imageUri=data.getData();
				}
				break;
				
			case ConstConfig.TAKE_PICTURE:
				imageUri=AddDiseaseRecordFrag.this.imageUri;
				AddDiseaseRecordFrag.this.imageUri=null;
				break;
				
			default:
				break;
			}
			if (imageUri!=null) {
				String picPath = FileHelper.uri2Path(context, imageUri);
				File imgFile = new File(picPath);
				if (imgFile.exists() && imgFile.isFile() && imgFile.length() > 0 && imgFile.length() <= 3 * 1024 * 1024) {
					adapter.addBean(picPath);
					adapter.notifyDataSetChanged();
				} else if (imgFile.exists() && imgFile.isFile() && imgFile.length() > 3 * 1024 * 1024) {
					LoadingTip.showToast(context, "每张图片最大不能超过3兆！");
				}
			}
		} 
	}
	
	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
		if (adapter != null) {
			adapter.clear();
		}
	}
	
}
